import React, { useEffect, useState, useCallback, useRef } from 'react';
import { Splitter, Alert, Spin, Typography, Space, Button, Flex, Tooltip, Badge } from 'antd';
import { ChatInput } from './ChatInput';
import Computer from './Computer';
import { useParams, useNavigate } from 'react-router-dom';
import { createConversation, getConversationById, ConversationDTO } from '@/api/conversation';
import { getMessagesByConversation } from '@/api/message';
import { Agent, getAgentById } from '@/api/agent';
import { AgentMessage, Bubble, Welcome, Prompts, Attachments } from "@/components";
import { 
  EllipsisOutlined, 
  ShareAltOutlined, 
  CopyOutlined, 
  BookOutlined, 
  StarOutlined, 
  LikeOutlined,
  RobotOutlined 
} from "@ant-design/icons";
import { chatRoles, placeholderPromptsItems } from "../constants";
import MarkdownIt from "markdown-it";
import type { GetProp } from "antd";
import { useStreamChat } from '../hooks/useStreamChat';

// ==================== 类型定义 ====================
interface ChatMessage {
  id: string;
  role: 'USER' | 'ASSISTANT';
  content: string;
  status: 'success' | 'error';
  reasonContent: string;
}

interface ChatResult {
  content: string;
  reasonContent: string;
}

// ==================== 工具函数 ====================
// 创建 markdown-it 实例
const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true,
  typographer: true,
});

/**
 * 渲染 Markdown 内容
 */
const renderMarkdown = (message: ChatMessage) => {
  return (
    <Typography>
        {
            message.reasonContent && (<div className='thinking'>
                <h3> 深度思考 </h3>
                <div
                    className="markdown-body markdown-body-reason"
                    dangerouslySetInnerHTML={{ __html: md.render(message.reasonContent) }}
                />
              </div>)
        }
      
      <div className="markdown-body markdown-body-content" dangerouslySetInnerHTML={{ __html: md.render(message.content) }} />
    </Typography>
  );
};

// ==================== 组件定义 ====================
const ChatComponent: React.FC = () => {
  // ==================== Hooks ====================
  const params = useParams<{ conversationId?: string; agentId?: string }>();
  const conversationId = params.conversationId;
  const agentId = params.agentId;
  const navigate = useNavigate();
  
  // ==================== State ====================
  // 输入与附件相关
  const [content, setContent] = useState('');
  const [headerOpen, setHeaderOpen] = useState(false);
  const [attachedFiles, setAttachedFiles] = useState<GetProp<typeof Attachments, 'items'>>([]);
  
  // 对话与消息相关
  const [conversation, setConversation] = useState<ConversationDTO | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [loadingHistory, setLoadingHistory] = useState(false);
  const [historyError, setHistoryError] = useState<string | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  
  // 智能体相关
  const [currentAgent, setCurrentAgent] = useState<Agent | null>(null);
  const [loadingAgent, setLoadingAgent] = useState(false);
  
  // 组件生命周期
  const componentMounted = useRef(true);
  
  // 流式聊天
  const { streamChat, streaming } = useStreamChat();
  
  // ==================== 生命周期 ====================
  // 组件挂载状态跟踪
  useEffect(() => {
    componentMounted.current = true;
    return () => {
      componentMounted.current = false;
    };
  }, []);

  // 获取智能体信息
  useEffect(() => {
    if (agentId) {
      setLoadingAgent(true);
      getAgentById(Number(agentId))
        .then(agent => {
          if (componentMounted.current) {
            setCurrentAgent(agent);
          }
        })
        .catch(error => {
          console.error('获取智能体信息失败:', error);
        })
        .finally(() => {
          if (componentMounted.current) {
            setLoadingAgent(false);
          }
        });
    } else {
      setCurrentAgent(null);
    }
  }, [agentId]);

  // ==================== 消息与对话管理 ====================
  /**
   * 重置消息列表
   */
  const resetMessages = useCallback(() => {
    setMessages([]);
    setHistoryError(null);
  }, []);

  /**
   * 监听路由变化，处理消息
   */
  useEffect(() => {
    // 首页状态
    if (!conversationId || conversationId === 'undefined') {
      resetMessages();
      setConversation(null);
      setIsProcessing(false); // 重置处理状态
      return;
    }
    
    // 加载现有会话
    if (conversationId) {
      // 设置加载状态
      setConversation({
        id: conversationId,
        title: '加载中...'
      });

      // 获取会话详情
      getConversationById(conversationId)
        .then(conversationData => {
          if (componentMounted.current) {
            setConversation(conversationData);
            setIsProcessing(false); // 获取完成后重置状态
          }
        })
        .catch(error => {
          console.error('获取会话信息失败:', error);
          if (componentMounted.current) {
            setConversation({ 
              id: conversationId, 
              title: '未知会话'
            });
            setIsProcessing(false); // 错误时也要重置状态
          }
        });
    }
  }, [conversationId, resetMessages]);

  /**
   * 加载会话历史消息
   */
  useEffect(() => {
    // 已经有消息的情况
    if (messages.length > 0) {
      setIsProcessing(false); // 已有消息，无需加载，重置状态
      return;
    }
    
    const loadMessages = async () => {
      if (!conversation?.id) {
        setIsProcessing(false); // 不需要加载消息时重置状态
        return;
      }

      setLoadingHistory(true);
      setHistoryError(null);

      try {
        const historyMessages = await getMessagesByConversation(conversation.id);
        
        if (!historyMessages || historyMessages.length === 0) {
          setMessages([]);
          if (componentMounted.current) {
            setLoadingHistory(false);
            setIsProcessing(false); // 加载完成但无消息时重置状态
          }
          return;
        }

        // 按创建时间排序
        const sortedMessages = historyMessages.sort((a, b) => 
          new Date(a.createTime).getTime() - new Date(b.createTime).getTime()
        );
        
        // 转换为内部消息格式
        const formattedMessages = sortedMessages.map(msg => ({
          id: msg.id,
          role: msg.role,
          content: msg.content || '',
          reasonContent: msg.reasonContent || '',
          status: 'success',
        }));

        if (componentMounted.current) {
          setMessages(formattedMessages as ChatMessage[]);
          setLoadingHistory(false);
          setIsProcessing(false); // 加载完成后重置状态
        }
      } catch (error) {
        console.error('加载历史消息失败:', error);
        if (componentMounted.current) {
          setHistoryError('加载历史消息失败，请稍后重试');
          setLoadingHistory(false);
          setIsProcessing(false); // 错误时也重置状态
        }
      } finally {
        if (componentMounted.current) {
          setLoadingHistory(false);
          setIsProcessing(false); // 确保无论如何都重置状态
        }
      }
    };

    loadMessages();
  }, [conversation?.id, messages.length]);

  // ==================== 消息处理 ====================
  /**
   * 处理发送消息
   */
  const handleSubmit = async (messageContent: string, targetConversationId: string) => {
    if (!messageContent || !targetConversationId) return;
    
    const aiMessageId = Date.now().toString();
    const userMessageId = `${Date.now()}_u`;

    try {
      // 添加用户消息
      const userMessage: ChatMessage = {
        id: userMessageId,
        role: 'USER',
        content: messageContent,
        status: 'success',
        reasonContent: ''
      };

      // 添加一个空的 AI 消息用于实时更新
      const aiMessage: ChatMessage = {
        id: aiMessageId,
        role: 'ASSISTANT',
        content: '',
        status: 'success',
        reasonContent: ''
      };
     
      // 添加消息到列表
      setMessages(prev => [...prev, userMessage, aiMessage]);

      // 处理 AI 响应
      await streamChat(
        messageContent, 
        targetConversationId, 
        ({content, reasonContent}: ChatResult) => {
          // 更新 AI 消息内容
          setMessages(prev => prev.map(msg => 
            msg.id === aiMessageId 
              ? { ...msg, content, reasonContent }
              : msg
          ));
          setIsProcessing(false);
        },
        // 传递智能体ID
        currentAgent?.id
      );

      // 清空输入框
      setContent('');
      // 消息发送成功后关闭附件面板
      setHeaderOpen(false);
    } catch (error) {
      console.error('发送消息失败:', error);
      // 更新消息状态为错误
      if (componentMounted.current) {
        setMessages(prev => prev.map(msg => 
          msg.id === aiMessageId 
            ? { ...msg, status: 'error' }
            : msg
        ));
        setIsProcessing(false);
      }
    } finally {
      // 确保无论如何都重置处理状态
      if (componentMounted.current) {
        setIsProcessing(false);
      }
    }
  };

  /**
   * 创建新会话
   */
  const createNewConversation = async (messageContent: string): Promise<string> => {
    const title = currentAgent 
      ? `与${currentAgent.name}的对话` 
      : messageContent.slice(0, 30);
    
    const newConversation = await createConversation({
      title,
      ...(currentAgent?.id && { agentId: currentAgent.id })
    });
    
    return newConversation.id;
  };

  /**
   * 处理消息发送 - 包含创建会话和路由跳转的逻辑
   */
  const handleMessageSubmit = async (text: string) => {
    if (!text) return;
    
    try {
      setIsProcessing(true);
      
      if (!conversationId) {
        // 创建新会话
        const newConversationId = await createNewConversation(text);
        
        // 设置新会话信息
        setConversation({
          id: newConversationId,
          title: text.slice(0, 30)
        });
        
        // 发送消息
        await handleSubmit(text, newConversationId);
        
        // 导航到新会话
        navigate(`/chat/${newConversationId}`, { replace: true });
      } else {
        // 已有会话，直接发送
        await handleSubmit(text, conversationId);
      }
    } catch (error) {
      console.error('处理消息提交失败:', error);
      setIsProcessing(false);
    }
  };

  // ==================== 事件处理 ====================
  /**
   * 处理文件变更
   */
  const handleFileChange = (info: any) => setAttachedFiles(info.fileList);

  /**
   * 处理提示词点击
   */
  const handlePromptsItemClick = (info: any) => {
    const description = info.data?.description;
    if (typeof description === 'string') {
      handleMessageSubmit(description);
    }
  };

  // ==================== 渲染函数 ====================
  /**
   * 获取欢迎页面节点
   */
  const getWelcomeNode = () => {
    if (currentAgent) {
      return (
        <Space direction="vertical" size={16} style={{ width: "100%" }}>
          <Welcome
            variant="borderless"
            icon={<RobotOutlined style={{ fontSize: 48, color: '#1890ff' }} />}
            title={`你好，我是${currentAgent.name}`}
            description={`版本: ${currentAgent.version || 1} | 状态: ${currentAgent.status || '活跃'}`}
            extra={
              <Space>
                <Button 
                  onClick={() => navigate('/agent')} 
                  icon={<RobotOutlined />}
                >
                  返回智能体列表
                </Button>
                <Button icon={<ShareAltOutlined />} />
              </Space>
            }
          />
          <Alert
            message="智能体系统提示词"
            description={
              <Typography.Paragraph ellipsis={{ rows: 3, expandable: true, symbol: '展开' }}>
                {currentAgent.systemPrompt}
              </Typography.Paragraph>
            }
            type="info"
            showIcon
          />
          <Prompts
            title="你想问什么？"
            items={placeholderPromptsItems}
            styles={{
              list: {
                width: "100%",
              },
              item: {
                flex: 1,
              },
            }}
            onItemClick={handlePromptsItemClick}
          />
        </Space>
      );
    }
    
    return (
      <Space direction="vertical" size={16} style={{ width: "100%" }}>
        <Welcome
          variant="borderless"
          icon="https://mdn.alipayobjects.com/huamei_iwk9zp/afts/img/A*s5sNRo5LjfQAAAAAAAAAAAAADgCCAQ/fmt.webp"
          title="Hello, I'm One Agent"
          description="Base on Ant Design, AGI product interface solution, create a better intelligent vision~"
          extra={
            <Space>
              <Button icon={<ShareAltOutlined />} />
              <Button icon={<EllipsisOutlined />} />
            </Space>
          }
        />
        <Prompts
          title="Do you want?"
          items={placeholderPromptsItems}
          styles={{
            list: {
              width: "100%",
            },
            item: {
              flex: 1,
            },
          }}
          onItemClick={handlePromptsItemClick}
        />
      </Space>
    );
  };

  /**
   * 生成气泡项
   */
  const getBubbleItems = (): GetProp<typeof Bubble.List, "items"> => {
    return messages.map((message) => {
      const { id, status, role } = message;
      
      return {
        key: id,
        loading: status !== "success",
        role: role,
        content: message,
        typing: { step: 1, interval: 2 },
        messageRender: () => renderMarkdown(message),
        footer: (
          <Flex>
            <Tooltip title="复制原文(markdown)">
              <Button size="small" type="text" icon={<CopyOutlined />} className="chat-button" />
            </Tooltip>
            <Tooltip title="复制内容(显示内容)">
              <Button size="small" type="text" icon={<BookOutlined />} className="chat-button" />
            </Tooltip>
            <Tooltip title="收藏">
              <Button size="small" type="text" icon={<StarOutlined />} className="chat-button" />
            </Tooltip>
            <Tooltip title="点赞">
              <Button size="small" type="text" icon={<LikeOutlined />} className="chat-button" />
            </Tooltip>
            <Tooltip title="分享">
              <Button size="small" type="text" icon={<ShareAltOutlined />} className="chat-button" />
            </Tooltip>
          </Flex>
        ),
      };
    });
  };

  /**
   * 处理消息渲染
   */
  const renderChatContent = () => {
    if (historyError) {
      return (
        <Alert
          message="加载历史消息失败"
          description={historyError}
          type="error"
          showIcon
          style={{ marginBottom: 16 }}
        />
      );
    }

    if (loadingHistory) {
      return (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center',
          height: '100%'
        }}>
          <Spin tip="加载历史消息中..." />
        </div>
      );
    }

    // 有消息就显示消息
    if (messages.length > 0) {
      return <Bubble.List items={getBubbleItems()} roles={chatRoles} />;
    }

    // 有对话ID但无消息，显示空消息状态
    if (conversation?.id) {
      return (
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center',
          height: '100%',
          color: '#999'
        }}>
          <p>暂无消息，开始聊天吧</p>
        </div>
      );
    }

    // 默认显示欢迎页
    return (
      <Bubble.List
        items={[{ content: getWelcomeNode(), variant: "borderless" }]}
        roles={chatRoles}
      />
    );
  };

  // ==================== 组件渲染 ====================
  return (
    <Splitter style={{
      height: '100vh',
      background: '#fff',
      boxShadow: '0 0 10px rgba(0, 0, 0, 0.1)'
    }}>
      <Splitter.Panel defaultSize="40%" collapsible>
        <div style={{
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          background: '#fff'
        }}>
          <div style={{
            flex: 1,
            overflow: 'auto',
            padding: '24px'
          }}>
            {renderChatContent()}
          </div>
          <div style={{
            padding: '24px',
          }}>
            <ChatInput
              content={content}
              loading={streaming || loadingHistory || isProcessing}
              headerOpen={headerOpen}
              attachedFiles={attachedFiles}
              onSubmit={handleMessageSubmit}
              onChange={setContent}
              onHeaderOpenChange={setHeaderOpen}
              onFileChange={handleFileChange}
              onPromptsItemClick={handlePromptsItemClick}
            />
          </div>
        </div>
      </Splitter.Panel>
      <Splitter.Panel>
        <Computer />
      </Splitter.Panel>
    </Splitter>
  );
};

export default ChatComponent; 